package com.example.myapplication.MessagePacket;

import com.example.myapplication.Coder.Util;

import java.io.UnsupportedEncodingException;

/**
 * @author gg_boy
 * @version $Rev$
 * @des ${TODO}
 * @updateAuther $Auther$
 * @updateDes ${TODO}
 */
public class SearchFriendPacket extends Packet{
    private String sendUser;

    public SearchFriendPacket(String sendUser) {
        this.sendUser = sendUser;
    }

    public SearchFriendPacket() {}
    @Override
    public int getPacketType() {
        return super.getPacketType();
    }

    @Override
    public void setPacketType(int packetType) {
        super.setPacketType(packetType);
    }

    @Override
    public void decode(byte[] buffer) throws UnsupportedEncodingException {
        int start_pos = 4;
        // 获取长度
        int length = Util.bytes2int(buffer, start_pos);
        start_pos += 4;

        this.sendUser = new String(buffer, start_pos, length, "UTF-8");
        start_pos += length;

    }

    @Override
    public byte[] encode() throws UnsupportedEncodingException {
        int sendUserLength = this.sendUser.getBytes("UTF-8").length;
        int totalLength = 4 + 4 + sendUserLength;
        byte[] buffer = new byte[totalLength];
        int offset = 0;

        // add packet type to buffer
        System.arraycopy(Util.int2bytes(Util.PACKET_SEARCH_FRIEND), 0, buffer, offset, 4);
        offset += 4;

        // the four bytes store send user name length
        System.arraycopy(Util.int2bytes(sendUserLength), 0, buffer, offset, 4);
        offset += 4;

        // copy send user to buffer
        System.arraycopy(sendUser.getBytes("UTF-8"), 0, buffer, offset, sendUserLength);
        offset += sendUserLength;

        return buffer;
    }

    @Override
    public void process() {
        super.process();
    }

    @Override
    public String toString() {
        return "SearchFriendPacket{" +
                "sendUser='" + sendUser + '\'' +
                '}';
    }
}
